import traceback

from flask import Blueprint, jsonify, request, url_for, current_app

from app.server.lstm_model import LSTMForecaster

train_lstm_bp = Blueprint('lstm_train', __name__)


@train_lstm_bp.route('/train_lstm', methods=['GET'])
def train_lstm_model():
    try:
        # 从URL参数获取配置
        args = request.args
        target_col = args.get('target', 'guilin_temp')
        test_size = float(args.get('test_size', 0.2))
        epochs = int(args.get('epochs', 100))
        batch_size = int(args.get('batch_size', 64))
        look_back = int(args.get('look_back', 180))
        forecast_horizon = int(args.get('forecast_horizon', 90))

        # 初始化并配置模型
        forecaster = LSTMForecaster(target_col=target_col)
        forecaster.look_back = look_back
        forecaster.forecast_horizon = forecast_horizon

        # 数据准备与训练
        forecaster.train_test_split(test_size=test_size)
        forecaster.build_model()
        history = forecaster.train(epochs=epochs, batch_size=batch_size)

        # 评估结果
        eval_result = forecaster.evaluate()

        return jsonify({
            'status': 'success',
            'metrics': eval_result['metrics'],
            'plots': {
                'training': url_for('static', filename='results/lstm_forecast/training_history.png')
            },
            'model': url_for('static', filename='saved_models/LSTM/new_best_model.h5'),
            'params': {
                'epochs': epochs,
                'batch_size': batch_size,
                'test_size': test_size,
                'look_back': look_back,
                'forecast_days': forecast_horizon
            }
        })

    except Exception as e:
        current_app.logger.error(f"训练失败: {str(e)}")
        return jsonify({
            'status': 'error',
            'message': f'训练失败: {str(e)}',
            'details': traceback.format_exc().splitlines()[-1]
        }), 500
